package com.example.md.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.md.common.Result;
import com.example.md.common.enums.UserEnum;
import com.example.md.dto.user.GenerateAdminReqDTO;
import com.example.md.dto.user.LoginReqDTO;
import com.example.md.dto.user.LoginResDTO;
import com.example.md.dto.user.LoginStatus;
import com.example.md.service.UserService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/generate-admin")
    public Result<JSONObject> generateAdmin(@RequestBody @Validated GenerateAdminReqDTO requestBody) throws IOException, MethodArgumentNotValidException {
        // String path = UserController.class.getClassLoader().getResource("admin.json").getPath();
        JSONObject jsonObject = userService.getAdmin();
        if (jsonObject != null) {
            return Result.failed("已经存在管理员用户，请勿重新注册");
        } 

        // 将 GenerateAdminReqDTO 的值，写入到 admin.json
        jsonObject = new JSONObject();
        jsonObject.set("username", requestBody.getUsername());
        jsonObject.set("password", requestBody.getPassword());
        jsonObject.set("email", requestBody.getEmail());

        File file = new File("admin.json");
        FileUtil.writeUtf8String(jsonObject.toString(), file);
        
        return Result.success(jsonObject);
    }
    
    @Autowired
    private LoginStatus loginStatus;

    /**
     * 用户登录
     * @param user 用户信息
     */
    @PostMapping("/login")
    public Result<LoginResDTO> login(@RequestBody @Validated LoginReqDTO requestBody) throws Exception {
        JSONObject jsonObject = userService.getAdmin();
        if (jsonObject == null || jsonObject.getStr("username") == null) {
            return Result.failed("管理员用户不存在");
        }

        String username = jsonObject.getStr("username");
        String password = jsonObject.getStr("password");
        if (!(username.equals(requestBody.getUsername()) && password.equals(requestBody.getPassword()))) {
            return Result.failed("用户名或密码不正确");
        }
        
        List<String> tokens = loginStatus.getTokens();
        if (tokens.size() >= 3) {
            tokens.remove(0);
        }
        String token = RandomUtil.randomString(16) + System.currentTimeMillis();
        tokens.add(token);

        LoginResDTO result = LoginResDTO.builder().username(username).token(token).build();
        System.out.println(loginStatus);
        
        return Result.success(result);
    }

    @GetMapping("/token")
    public Result<LoginResDTO> getUserByToken(@RequestHeader("token") String token) throws Exception {
        JSONObject jsonObject = userService.getAdmin();
        if (jsonObject == null) {
            return Result.failed(UserEnum.ADMIN_NOT_EXIST);
        }

        System.out.println("token: " + token);
        if (!loginStatus.getTokens().contains(token)) {
            return Result.failed("token 已失效或不存在");
        }
        
        LoginResDTO result = LoginResDTO.builder().username(loginStatus.getUsername()).token(token).build();
        return Result.success(result);
    }
}
